package persistence

import (
	"fmt"
	"time"
	"context"
	"zxstudy.com/domain/repository"
	"zxstudy.com/infrastructure/ent"
	"github.com/facebook/ent/dialect/sql"
	_ "github.com/go-sql-driver/mysql"
)

type Repositories struct {
	client 	*ent.Client
	ctx 	context.Context
	User 	repository.UserRepository
	Group 	repository.GroupRepository
	Car 	repository.CarRepository
}

func NewRepository(client *ent.Client) *Repositories {
	return &Repositories{
		client: client,
		ctx: context.Background(),
		User: NewUserRepository(client),
		Group: NewGroupRepository(client),
		Car: NewCarRepository(client),
	}
}

/*
 * 连接数据库
 */
func Open(host, dbname, user, pass, charset string, port int) (*Repositories, error) {
	drv, err := sql.Open("mysql", fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=%s&parseTime=true", user, pass, host, port, dbname, charset))
	if err != nil {
		return nil, err
	}
	
	db := drv.DB()
	db.SetMaxIdleConns(10)
	db.SetMaxOpenConns(50)
	db.SetConnMaxLifetime(time.Hour)
	client := ent.NewClient(ent.Driver(drv))
	
	return NewRepository(client), nil
}

func (repo *Repositories) Automigrate() error {
	return repo.client.Schema.Create(repo.ctx);
}

/*
 * 关闭数据库
 */
func (repo *Repositories) Close() {
	repo.client.Close()
}